﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XukaShop.Biz;
using XukaShop.Common;
using XukaShop.Models.Entities;

namespace XukaShop.Areas.Admin.Controllers
{
    public class PromotionController : Controller
    {
        private PromotionBiz _promotionBiz = new PromotionBiz();

        [HttpGet]
        public ActionResult Index()
        {
            List<Promotion> lstPromotion = new List<Promotion>();
            lstPromotion = _promotionBiz.GetListPromotions();
            return View(lstPromotion);
        }

        [HttpGet]
        public ActionResult PromotionDetail(int? promotionId)
        {
            Promotion promotion = new Promotion();
            if (promotionId.HasValue)
            {
                promotion = _promotionBiz.GetPromotionById(promotionId.Value);
            }

            // List all status of promotion -> this is used to load combobox
            ViewBag.ListPromotionStatus = _promotionBiz.GetListPromotionStatus();
            return View(promotion);
        }

        /// <summary>
        /// Save all product information
        /// </summary>
        /// <param name="productModel"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SavePromotion(Promotion promotionModel)
        {
            bool isUpdate = false;
            int promotionId = 0;
            // Update or Insert
            if (promotionModel.Id != 0)
            {
                isUpdate = true;
            }
            var isSaveSuccess = _promotionBiz.SavePromotion(promotionModel, isUpdate);
            // If Save general information successful
            if (isSaveSuccess)
            {
                // If Insert new product, get product code
                if (promotionModel.Id == 0)
                {
                    var promotionSaved = _promotionBiz.GetPromotionByName(promotionModel.Name);
                    promotionId = promotionSaved.Id;
                }
                else
                {
                    promotionId = promotionModel.Id;
                }
                return Json(new { Result = CommonConst.SUCCESSFUL, PromotionId = promotionId }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { Result = CommonConst.FAIL, PromotionId = promotionId }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public string DeletePromotion(int promotionId)
        {
            if (promotionId == 0)
            {
                return CommonConst.FAIL;
            }
            var isSuccessDelete = _promotionBiz.DeletePromotion(promotionId);
            if (isSuccessDelete)
            {
                return CommonConst.SUCCESSFUL;
            }
            return CommonConst.FAIL;
        }
    }
}
